package com.damai.action.json;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.citywithincity.api.entities.Customer;
import com.citywithincity.utils.JsonUtil;
import com.damai.action.IParamParser;
import com.damai.action.IParamParserFactory;
import com.damai.action.NoinputError;
import com.damai.action.json.ParamGetterFactory.IParamGetterFactory;

import javassist.ClassPool;

public class SimpleJsonParamParserFactory implements IParamParserFactory, IGetJson, IParamGetterFactory {

	private static final Log logger = LogFactory.getLog(SimpleJsonParamParserFactory.class);

	private static final SimpleJsonParamParserFactory DEFAULT = new SimpleJsonParamParserFactory();

	public static final SimpleJsonParamParserFactory getDefault() {
		return DEFAULT;
	}

	protected SimpleJsonParamParserFactory() {

	}

	@Override
	public IParamParser createParser( ClassPool classPool, Class<?> controllerClass, Method method) {
		return new JsonParam(this, ParamGetterFactory.createParamGetter(classPool,  controllerClass, method, this));
	}

	@Override
	public Map<String, Object> getJson(HttpServletRequest request) throws IOException {
		try {
			return JsonUtil.read(request.getReader());
		} catch (IOException e) {
			logger.info("NoinputError");
			throw new NoinputError();
		}

	}

	@Override
	public IParamGetter createGetter(Class<?> controller, Method method, String name, Class<?> type,
			Class<?> paramType) {
		if (type == Customer.class) {
			return new SimpleParamGetter(name);
		}
		return null;
	}

}
